package com.liuhaoqi.raletiveblog.controller;

import com.github.pagehelper.PageInfo;
import com.liuhaoqi.raletiveblog.entity.Blog;
import com.liuhaoqi.raletiveblog.entity.Category;
import com.liuhaoqi.raletiveblog.entity.Tag;
import com.liuhaoqi.raletiveblog.entity.User;
import com.liuhaoqi.raletiveblog.entity.dto.BlogDto;
import com.liuhaoqi.raletiveblog.result.BlogPageResult;
import com.liuhaoqi.raletiveblog.result.PageResult;
import com.liuhaoqi.raletiveblog.result.WebRestResult;
import com.liuhaoqi.raletiveblog.result.business.PageResult.AddBlogPageResult;
import com.liuhaoqi.raletiveblog.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @Author liuhaoqi
 * @Date 2020/4/18 13:47
 * @Version 1.0
 */
@Controller
public class ArticleController {
    @Autowired
    BlogService blogService;
    @Autowired
    MemoryService memoryService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    TagService tagService;
    @Autowired
    UserService userService;

    @GetMapping("/article")
    public String toArticle(Model model, @RequestParam(defaultValue = "1",value = "pageNum") String pageNum,
                            @RequestParam(defaultValue = "8",value = "pageSize") String pageSize) {
        //请求后端数据库查询得到所有博客数据并返回给前端
        PageInfo<BlogDto> blogList = blogService.getBlogList(pageNum, pageSize);

        List<BlogDto> blogListNoFenYe = blogService.getBlogListNoFenYe();
        //分类导航,查出所有分类返回给前端
        List<Category> categoryList = categoryService.getCategoryList();
        model.addAttribute("categoryList",categoryList);
        model.addAttribute("blogs",blogList);
        model.addAttribute("blogListNoFenYe",blogListNoFenYe);
        return "article";
    }



    /**
     * 文章管理 - 新增文章
     * @param model
     * @return
     */
    @GetMapping("/admin/blogsAdd")
    public String blogsAdd(Model model) {
        return "admin/blogsAdd";
    }

    @GetMapping("/getCategoryList")
    @ResponseBody
    public PageResult<Category> getCategoryList() {
        List<Category> categoryList = categoryService.getCategoryList();
        PageResult<Category> result = new PageResult<>();
        result.setData(categoryList);
        return result;
    }

    @GetMapping("/getTagsList")
    @ResponseBody
    public PageResult<Tag> getTagsList() {
        List<Tag> tagList = tagService.getTagList();
        PageResult<Tag> result = new PageResult<>();
        result.setData(tagList);
        return result;
    }

    @PostMapping("/publishArticle")
    @ResponseBody
    public WebRestResult addBlog(@RequestParam("title") String title,
                                 @RequestParam("category") String categoryname,
                                 @RequestParam("tags") String tags,
                                 @RequestParam("image") String image,
                                 @RequestParam("description") String description,
                                 @RequestParam("content") String content,
                                 @RequestParam("reference") String reference) {
        Category category1 = new Category();
        Blog blog = new Blog();
        blog.setTitle(title);
        Category category = categoryService.getCategoryByCategoryName(categoryname);
        if ( category == null) {
            //如果分类在数据库中没有，就先保存到数据库中
            category1.setCategoryname(categoryname);
            int flag = categoryService.insertCategory(category1);
            blog.setTypeId(category1.getCategoryid());
        } else {
            blog.setTypeId(category.getCategoryid());
        }
        blog.setContent(content);
        blog.setTagIds(tags);
        if (reference.equals("1")) {
            blog.setUserId(1L);
            blog.setFlag("原创");
        } else {
            blog.setUserId(2L);
            blog.setFlag("转载");
        }
        blog.setDescription(description);
        blog.setFirstPicture(image);
        blog.setAppreciation(1);
        blog.setCommentabled(1);
        blog.setPublished(1);
        blog.setRecommend(1);
        blog.setShareStatement(1);
        blog.setCreateTime(new Date());
        blog.setUpdateTime(new Date());
        blog.setViews(0);
        blog.setCommentnum(0);
        int flag = blogService.insertBlog(blog);
        //将标签和博客文章id插入数据表 标签是以空格分割出的
        String [] tagarr = tags.split("\\s+");
        //查询出刚才插入的博客id
        Long newBlogId=blogService.getBlogByCreateTime();
        for (String tagname : tagarr) {
            Tag tag = new Tag();
            tag.setBlogclassId(newBlogId);
            tag.setTagname(tagname);
            tagService.insertTag(tag);
        }
        WebRestResult result = new WebRestResult();
        if (flag >= 0) {
            result.setMessage("发布文章成功！");
            result.setResult(WebRestResult.SUCCESS);
        } else {
            result.setMessage("发布文章失败！");
            result.setResult(WebRestResult.FAILURE);
        }
        return result;
    }


    @GetMapping("/admin/blogsList")
    public String blogsList(Model model) {
        return "admin/blogsList";
    }


    @GetMapping("/admin/getBlogsList")
    @ResponseBody
    public BlogPageResult<AddBlogPageResult> getAdminBlogDtoList(@RequestParam(defaultValue = "1",value = "pageNum") int pageNum,
                                                                 @RequestParam(defaultValue = "10",value = "pageSize") int pageSize) {
        int start=(pageNum-1)*pageSize;
        int end=pageSize;
        //重写一个查询方法 ，来查询出博客文章的所有详情信息
        List<AddBlogPageResult> adminBlogDtoList = blogService.getAdminBlogDtoList(start,end,pageSize);
        if (adminBlogDtoList.size()>0) {
            for (AddBlogPageResult addBlogPageResult : adminBlogDtoList) {
                addBlogPageResult.setTags(tagService.getTagListByTagId(addBlogPageResult.getId()));
            }
        }
        BlogPageResult<AddBlogPageResult> result = new BlogPageResult<>();
        result.setCode(0);
        result.setMsg("获取博客信息成功！");
        int cnt=adminBlogDtoList.get(0).getCnt();
        result.setCount(cnt);
        result.setData(adminBlogDtoList);
        return result;
    }

    @PostMapping("/admin/deleteBlogByBlogId")
    @ResponseBody
    public WebRestResult deleteBlogByBlogId(@RequestParam("blogId") Long blogId) {
        WebRestResult result = new WebRestResult();
        int flag = blogService.deleteBlogByBlogId(blogId);
        if (flag > 0) {
            result.setResult(WebRestResult.SUCCESS);
            result.setMessage("删除id为" + blogId + "的博客成功！");
        } else {
            result.setResult(WebRestResult.FAILURE);
            result.setMessage("删除id为" + blogId + "的博客失败！");
        }
        return result;
    }

    @PostMapping("/updateBlogByblogId")
    @ResponseBody
    public WebRestResult updateBlogByblogId(@RequestParam("blogId") Long blogId,
                                            @RequestParam("title") String title,
                                            @RequestParam("username") String username,
                                            @RequestParam("categoryname") String categoryname,
                                            @RequestParam("firstPicture") String firstPicture,
                                            @RequestParam("description") String description,
                                            @RequestParam("tags") String tags) {
        Category category = categoryService.getCategoryByCategoryName(categoryname);
        //如果更新的分类为空的话，更新数据库这个新分类和blogId
        if (category == null) {
            Category category1 = new Category();
            category1.setCategoryname(categoryname);
            category1.setCategoryid(blogService.getDetailBlog(blogId).getTypeId());
            categoryService.updateCategoryByCategoryId(category1);
        }
        //如果更新的用户名不存在的话，就将这个用户名和文章博客对应的userid更新到数据库里
        User user = userService.getUserByUsername(username);
        if (user == null) {
            User user1 = new User();
            user1.setId(blogService.getDetailBlog(blogId).getUserId());
            user1.setUsername(username);
            userService.updateUserByUserId(user1);
        }
        //将标签和博客文章id插入数据表 标签是以空格分割出的
        String [] tagarr = tags.split("\\s+");
        for (String tagname : tagarr) {
            Tag tag = new Tag();
            tag.setBlogclassId(blogId);
            tag.setTagname(tagname);
            tagService.insertTag(tag);
        }
        Blog blog = new Blog();
        blog.setTitle(title);
        blog.setId(blogId);
        blog.setFirstPicture(firstPicture);
        blog.setDescription(description);
        blog.setUpdateTime(new Date());
        int i = blogService.updateBlog(blog);
        WebRestResult result = new WebRestResult();
        if (i > 0) {
            result.setResult(WebRestResult.SUCCESS);
            result.setMessage("修改博客成功！");
        } else {
            result.setResult(WebRestResult.FAILURE);
            result.setMessage("修改博客失败！");
        }
        return result;
    }

}
